package syncer

import (
	"context"
	"log"
	"net/http"
	"time"
)

/*
	syncer do some thing need to do period
*/
func Install(ctx context.Context) error {
	go func() {
		tk := time.NewTicker(time.Minute)
		//tk := time.NewTicker(time.Second*10)
		for {
			select {
			case <-ctx.Done():
				return
			case <-tk.C:
				updateTree()
				updateDag()
				updateInstanceContainer()
			}
		}
	}()
	return nil
}

//func login() {
//	if _, err := http.Get("http://localhost:8080/apis/organize/tree/build"); err != nil {
//		log.Printf("update tree %v", err)
//	}
//}

func updateTree() {
	req, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/apis/organize/tree/build", nil)
	req.Header.Add("token", token)
	if _, err := http.DefaultClient.Do(req); err != nil {
		log.Printf("update tree %v", err)
	}
}

func updateDag() {
	req, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/apis/instance/dag/update", nil)
	req.Header.Add("token", token)
	if _, err := http.DefaultClient.Do(req); err != nil {
		log.Printf("update dag %v", err)
	}
}

func updateInstanceContainer() {
	req, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/apis/instance/update/container", nil)
	req.Header.Add("token", token)
	if _, err := http.DefaultClient.Do(req); err != nil {
		log.Printf("update container %v", err)
	}
}

var token = `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJvd25lciI6IiIsIm5hbWUiOiIiLCJjcmVhdGVkVGltZSI6IiIsInVwZGF0ZWRUaW1lIjoiIiwiaWQiOiJjNmI2ZDY2My0yYWYwLTQ2ODctODgxNS01ZTg4ZDc4YmY4NDgiLCJ0eXBlIjoiIiwicGFzc3dvcmQiOiIiLCJwYXNzd29yZFNhbHQiOiIiLCJkaXNwbGF5TmFtZSI6IiIsImF2YXRhciI6IiIsInBlcm1hbmVudEF2YXRhciI6IiIsImVtYWlsIjoiIiwicGhvbmUiOiIiLCJsb2NhdGlvbiI6IiIsImFkZHJlc3MiOm51bGwsImFmZmlsaWF0aW9uIjoiIiwidGl0bGUiOiIiLCJpZENhcmRUeXBlIjoiIiwiaWRDYXJk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